/**
 * 常用方法封装文件上传，图片保存等
 **/
// import Vue from 'vue';
// import dayjs from 'dayjs';

import {
	timLogin
} from "@/utils/tim";

import config from './api/config.js'
import $api from './api/api.js'



const pageWhiteList = [
	'/', // 注意入口页必须直接写 '/'
	'/pages/entry/index',
	{
		pattern: /^\/pages\/Login\/*/
	},
	'/pages/views/packageB/scanCode',
	'/pages/views/packageB/type-jobhunting/PrivacyAndRules/yinsishuoming/fuwuxieyi',
	'/pages/views/packageB/type-jobhunting/PrivacyAndRules/yinsishuoming/yinsizhengce',
	'/pages/Home/index',
	'/pages/nzuanchan/index',
	'/pages/School/index',
]

const util = {
	/**
	 * 数组对象去重,根据key去重
	 * */
	uniqueKey(arr, key) {
		const map = new Map();
		for (const item of arr) {
			if (!map.has(item[key])) {
				map.set(item[key], item);
			}
		}
		return [...map.values()];
	},
	happenTimeFun(num) { //时间戳转时间 
		let date = new Date(num);
		//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let y = date.getFullYear();
		let MM = date.getMonth() + 1;
		MM = MM < 10 ? ('0' + MM) : MM; //月补0
		let d = date.getDate();
		d = d < 10 ? ('0' + d) : d; //天补0
		let h = date.getHours();
		h = h < 10 ? ('0' + h) : h; //小时补0
		let m = date.getMinutes();
		m = m < 10 ? ('0' + m) : m; //分钟补0
		let s = date.getSeconds();
		s = s < 10 ? ('0' + s) : s; //秒补0  
		return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
	},
	// 比较时间大小
	compareDate(date1, date2) {
		var oDate1 = new Date(date1);

		var oDate2 = new Date(date2);

		if (oDate1.getTime() > oDate2.getTime()) {
			return true; //第一个大
		} else {
			return false; //第二个大
		}
	},
	//推算日期  年
	getBeforeDateYear(date, yNum) { //年月日   
		var d = new Date(date);
		d.setFullYear(d.getFullYear() + yNum); //减n年  
		return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
	},
	//推算日期  月
	getBeforeDateMonth(date, monthNum, type = 3) { //时间  多少个月  返回年月日  2年月  
		var dateArr = date.split('-');
		var year = dateArr[0]; //获取当前日期的年份
		var month = dateArr[1]; //获取当前日期的月份
		var day = dateArr[2]; //获取当前日期的日
		var days = new Date(year, month, 0);
		days = days.getDate(); //获取当前日期中月的天数
		var year2 = year;
		var month2 = parseInt(month) + monthNum;
		if (month2 <= 0) {
			var absM = Math.abs(month2);
			year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
			month2 = 12 - (absM % 12);
		}
		var day2 = day;
		var days2 = new Date(year2, month2, 0);
		days2 = days2.getDate();
		if (day2 > days2) {
			day2 = days2;
		}
		if (month2 < 10) {
			month2 = '0' + month2;
		}
		if (type == 3) { //day2 日时分秒
			var t2 = year2 + '-' + month2 + '-' + day2;
			return t2;
		}
		if (type == 2) {
			var t2 = year2 + '-' + month2;
			return t2;
		}
		return "";
	},
	getBeforeDateMonthLastDay: (date, monthNum) => { //获取后一天日期
		let time = ''
		if (date) {
			time = new Date(date).getTime() + 24 * 60 * 60 * 1000;
		} else {
			time = new Date().getTime() + 24 * 60 * 60 * 1000;
		}
		let afterday = new Date(time);
		let month = afterday.getMonth();
		let day = afterday.getDate();
		return afterday = afterday.getFullYear() + "-" + (afterday.getMonth() >= 9 ? (afterday.getMonth() +
				1) :
			"0" +
			(afterday.getMonth() + 1)) + "-" + (afterday.getDate() > 9 ? (afterday.getDate()) : "0" + (
			afterday
			.getDate()));
	},
	/**
	 * date  推算时间
	 * minute  间隔（分） 
	 * type  返回年月日时分秒    6返回到秒   5返回到分  其他自己加
	 */
	//推算时间   分钟   add  是否往前
	getNowFormatDate(date, minute, type = 5) {
		var seperator1 = "-";
		var seperator2 = ":";
		//前十分钟时间
		var minutes = minute;
		var interTimes = minutes * 60 * 1000;
		var interTimes = parseInt(interTimes);
		date = new Date(Date.parse(date) + interTimes);
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		var hour = date.getHours();
		var minutes = date.getMinutes();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		if (hour >= 0 && hour <= 9) {
			hour = "0" + hour;
		}
		if (minutes >= 0 && minutes <= 9) {
			minutes = "0" + minutes;
		}
		var currentdate = "";
		if (type == 5) {
			currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
				" " + hour + seperator2 + minutes
		} else {
			currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
				" " + hour + seperator2 + minutes +
				seperator2 + date.getSeconds();
		}
		return currentdate;
	},
	//推算时间  天  倒推用负数
	getBeforeDateDay(date, n) {
		let d = new Date(date)
		let t = d.getTime(d)
		var time = t + n * 24 * 60 * 60 * 1000;
		var tragetTime = new Date(time);
		var month = tragetTime.getMonth();
		var day = tragetTime.getDate();
		tragetTime = tragetTime.getFullYear() + "-" + (tragetTime.getMonth() >= 9 ? (tragetTime.getMonth() + 1) :
			"0" +
			(tragetTime.getMonth() + 1)) + "-" + (tragetTime.getDate() > 9 ? (tragetTime.getDate()) : "0" + (
			tragetTime.getDate()));
		return tragetTime;
	},
	//获取当前的年月日时分秒
	getNowDate(type = 3) {
		let date = new Date();
		//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let y = date.getFullYear();
		let MM = date.getMonth() + 1;
		MM = MM < 10 ? ('0' + MM) : MM; //月补0
		let d = date.getDate();
		d = d < 10 ? ('0' + d) : d; //天补0
		let h = date.getHours();
		h = h < 10 ? ('0' + h) : h; //小时补0
		let m = date.getMinutes();
		m = m < 10 ? ('0' + m) : m; //分钟补0
		let s = date.getSeconds();
		s = s < 10 ? ('0' + s) : s; //秒补0

		switch (type) {
			case 1: //年  4位
				return y;
				break;
			case 2: //年月
				return y + '-' + MM;
				break;
			case 3: //年月日
				return y + '-' + MM + '-' + d;
				break;
			case 5: //年月日  时分
				return y + '-' + MM + '-' + d + ' ' + h + ':' + m;
				break;
			case 6: //年月日  时分秒
				return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
				break;
			case 7: //时分秒
				return h + ':' + m + ':' + s;
				break;
			default:
				return date.toLocaleString();
		}
	},
	//手机号格式
	isPhone: function(phone) {
		var pattern = /^1[34578]\d{9}$/;
		if (pattern.test(phone)) {
			return true;
		}
		return false;
	},

	// 判断是否是数字
	isValueNumber(val) {
		let value = val.replace('/(^\s*)|(\s*$)', '') //去除字符串前后空格
		let num = Number(value) //将字符串转换为数字
		if (isNaN(num)) { //判断是否是非数字
			return false
		} else if (value === '' || value === null) { //空字符串和null都会被当做数字
			return false
		} else {
			return true
		}
	},

	// 消息提示 弹框
	toast: function(text, duration, success) {
		//300 后执行  原因请求完成后0.3s执行uni.hideLoading()  会将showToast隐藏
		setTimeout(() => {
			uni.showToast({
				title: text || "出错啦~",
				icon: success ? 'success' : 'none',
				duration: duration || 2000,
				success: () => {}
			})
		}, 300)
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},

	/**
	 * 上传文件
	 * @param string src 文件路径
	 */
	AuploadFile: function(opts) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: config.domain.baseUrl + "/api/core/file/upload",
				filePath: opts.src,
				name: 'file',
				header: {
					'Authorization': uni.getStorageSync("access_token").token_type + " " +
						uni.getStorageSync("access_token").access_token,
				},
				success: function(res) {
					uni.hideLoading()
					if (res.statusCode == 200) {
						let data = JSON.parse(res.data)
						if (data.Success) {
							resolve(data)
						} else {
							util.toast("上传失败");
							resolve(data)
						}
					} else {
						util.toast("上传失败");
						resolve(data)
					}
				},
				fail: function(res) {
					uni.hideLoading()
					reject(res)
					util.toast(res);
				}
			})
		})
	},

	// 保存图片到相册 src 下载资源的src路径
	saveImageToPhotosAlbum(opts) {
		uni.downloadFile({
			url: opts.src,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function() {
							uni.showToast({
								title: "保存成功",
								duration: 2000
							});
						},
						fail: function() {
							// #ifdef APP-PLUS
							if (plus.os.name == 'iOS') { //如果拒绝了访问
								var PHPhotoLibrary = plus.ios.importClass('PHPhotoLibrary')
								var PHAuthorizationStatus = PHPhotoLibrary
									.authorizationStatus()
								if (PHAuthorizationStatus != 3) {
									uni.showModal({
										content: '需要访问您的相册，请在设置里开启',
										confirmText: '设置',
										success: res => {
											if (res.confirm) {
												plus.runtime.openURL(
													'app-settings://')
											}
										}
									});
								}
							}
							// #endif
							uni.showToast({
								title: "保存失败，请稍后重试",
								icon: "none"
							});
						}
					});
				}
			}
		})
	},

	/* 
	 username 账号，
	 password 密码
	 type  状态 
	 //登录
	 */
	HrcLogin(username, password, type) {
		uni.showLoading({
			title: '请稍候...'
		});
		let dataobj = {
			username: username,
			password: password,
			grant_type: "password",
			client_id: "hui_app",
			type: type ? type : ''
		}
		uni.request({
			url: config.domain.loginurl,
			method: "POST",
			header: {
				"content-type": "application/x-www-form-urlencoded",
			},
			data: dataobj,
			success: (res) => {
				uni.hideLoading();
				if (res.statusCode === 200) {
					//保存 access_token
					const token = res.data;
					const expires_at = Math.floor(token.expires_in) + Math.floor(Date.now() / 1000)
					token.expires_at = expires_at;
					uni.setStorageSync("access_token", token);
					// 登录信息 账号
					uni.setStorageSync("user_name", username);
					util.currentUser().then(() => {
						uni.navigateTo({
							url: "/pages/Login/selectIdentity",
						});
					}).catch((ex) => {
						console.log('登录 获取用户信息异常', ex)
						util.toast("网络不给力");
					})
				} else if (res.statusCode === 400) {
					util.toast(res.data.error_description);
				} else {
					util.toast(`登录失败!`);
				}
			},
			// 接口调用失败的回调函数
			fail(res) {
				util.toast("请稍后再试~");
				uni.hideLoading();
			}
		})
	},

	//tim退出登录
	timlogout() {
		const app = getApp();
		app.globalData.tim.isLogin = false;
		if (uni.$TUIKit) {
			uni.$TUIKit.logout().catch((error) => {})
		}
	},
	//退出登录
	tuiculogout() {
		const app = getApp();
		util.timlogout();
		uni.setStorageSync('access_token', "")
		uni.setStorageSync('homelist', "");
		uni.setStorageSync('NewlishijiluData', '')
		app.globalData.isLogin = false;

		uni.reLaunch({
			url: "/pages/Login/login"
		})
	},
	//获取登录信息
	currentUser() {
		const isLogin = util.checkHasToken();
		if (!isLogin) {
			return Promise.reject();
		}
		return new Promise((resolve, reject) => {
			const app = getApp();
			// Vue 上挂载属性的方式只支持vue页面，不能在 nvue页面中使用。改成引用api文件
			$api.core.accountcurrentUser({
				platformType: 4,
			}).then((res) => {
				if (res.Success) {
					let datalist = res.Result;
					// 当前角色 0求职者 1招聘者
					let type = true;
					datalist.CorpList.forEach((res) => {
						if (res.Id == datalist.UserExtendInfo.CurrentCorpId) {
							// 点击 的
							uni.setStorageSync("dianjiqiye", res);
						}
					});
					const userRole = res.Result.UserExtendInfo?.CurrentRole || 0; //0求职者 1招聘者
					app.globalData.user = res.Result.UserInfo;
					app.globalData.userRole = res.Result.UserExtendInfo?.CurrentRole;
					app.globalData.userCorpId = res.Result.UserExtendInfo?.CurrentCorpId;
					app.globalData.menus = res.Result.MenuList;
					app.globalData.permissions = res.Result.PermissionList;
					app.globalData.corps = res.Result.CorpList;
					app.globalData.userResume = res.Result.UserResumeInfo;
					if (userRole == 1) {
						let currentCorp = {};
						const corps = res.Result.CorpList;
						if (corps.length > 0) {
							let corpId = res.Result.UserExtendInfo?.CurrentCorpId;
							if (!corpId) {
								corpId = corps[0].Id;
							}
							const _index = corps.findIndex((x) => x.Id == corpId);
							if (_index > -1) {
								currentCorp = corps[_index];
							} else {
								currentCorp = corps[0];
							}
						}
						app.globalData.currentCorp = currentCorp;
						type = false;
					}
					app.globalData.isLoadUser = true;
					// 保存的全部信息
					uni.setStorageSync("homelist", datalist);
					// 企业还是个人
					uni.setStorageSync("type", type);
					//tim 登录
					timLogin();
					resolve()
				} else {
					reject()
				}
			}).catch((xx) => {
				reject(xx)
			});
		})
	},

	geocoderegeo(location) {
		// let location;
		return new Promise((resolve, reject) => {
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?key=ef98fef87aa9b2a353e8089128267ff0&location=${location}`, //逆地理编码接口地址。
				method: 'GET',
				success: (res) => {
					resolve(res)
				},
				fail(res) {
					reject(res)
				}
			})
		})
	},


	//设置tabbar
	setCustomTabbar() {
		const app = getApp();
		const userRole = app.globalData.userRole || 0;
		// 当前角色 0求职者 1招聘者
		if (userRole == 1) {
			// 设置 tabBar 的文本内容和图片路径
			uni.setTabBarItem({
				index: 0, // 索引，从 0 开始，指定第几个 tabBar
				text: "人才库", // 修改后的文本
				iconPath: "/static/tabBar/rencaiku.png",
				selectedIconPath: "/static/tabBar/rencaiku1.png",
			});
			uni.setTabBarItem({
				index: 1, // 索引，从 0 开始，指定第几个 tabBar
				text: "职位管理", // 修改后的文本
				iconPath: "/static/tabBar/zhiwei.png",
				selectedIconPath: "/static/tabBar/zhiwei1.png",
			});
			uni.setTabBarItem({
				index: 2, // 索引，从 0 开始，指定第几个 tabBar
				text: "简历管理", // 修改后的文本
				iconPath: "/static/tabBar/jianli.png",
				selectedIconPath: "/static/tabBar/jianli1.png",
			});
			uni.setTabBarItem({
				index: 3, // 索引，从 0 开始，指定第几个 tabBar
				text: "会话消息", // 修改后的文本
				iconPath: "/static/tabBar/zphuihua.png",
				selectedIconPath: "/static/tabBar/zphuihua1.png",
			});
			uni.setTabBarItem({
				index: 4, // 索引，从 0 开始，指定第几个 tabBar
				text: "我的", // 修改后的文本
				iconPath: "/static/tabBar/zpmy.png",
				selectedIconPath: "/static/tabBar/zpmy1.png",
			});
		} else {
			uni.setTabBarItem({
				index: 0, // 索引，从 0 开始，指定第几个 tabBar
				text: "首页", // 修改后的文本
				iconPath: "/static/tabBar/shouye.png",
				selectedIconPath: "/static/tabBar/shouye1.png",
			});
			uni.setTabBarItem({
				index: 1, // 索引，从 0 开始，指定第几个 tabBar
				text: "专场招聘", // 修改后的文本
				iconPath: "/static/tabBar/zhuanchang.png",
				selectedIconPath: "/static/tabBar/zhuanchang1.png",
			});
			uni.setTabBarItem({
				index: 2, // 索引，从 0 开始，指定第几个 tabBar
				text: "数字化学校", // 修改后的文本
				iconPath: "/static/tabBar/shuzihua.png",
				selectedIconPath: "/static/tabBar/shuzihua1.png",
			});
			uni.setTabBarItem({
				index: 3, // 索引，从 0 开始，指定第几个 tabBar
				text: "会话消息", // 修改后的文本
				iconPath: "/static/tabBar/huihua.png",
				selectedIconPath: "/static/tabBar/huihua1.png",
			});
			uni.setTabBarItem({
				index: 4, // 索引，从 0 开始，指定第几个 tabBar
				text: "我的", // 修改后的文本
				iconPath: "/static/tabBar/my.png",
				selectedIconPath: "/static/tabBar/my1.png",
			});
		}
		app.globalData.currentTabbarType = userRole;
	},
	//检测登录
	checkHasToken() {
		// const tokenResult = uni.getStorageSync("access_token")
		// if (tokenResult && tokenResult.access_token) {
		// 	return true;
		// } else {
		// 	return false
		// }
		let da = uni.getStorageSync("access_token")
		return da.access_token
	},

	//检测和加载用户信息等等
	async checkPage(url) {
		let pass = false
		if (url) {
			// 判断当前窗口是白名单，如果是则不重定向路由
			if (pageWhiteList) {
				pass = pageWhiteList.some((item) => {
					if (typeof(item) === 'object' && item.pattern) {
						return item.pattern.test(url)
					}
					return url === item
				})
			}
		} else {
			pass = true;
		}
		let da = uni.getStorageSync("access_token")
		const isLogin = da.access_token
		if (isLogin) {
			let app = getApp();
			const isLoadUser = app.globalData.isLoadUser;
			if (!isLoadUser) {
				await util.currentUser().catch(() => {})
			}
			app = getApp();
			//设置底部TabBar
			const userRole = app.globalData.userRole;
			const currentTabbarType = app.globalData.currentTabbarType;
			if (currentTabbarType !== userRole) {
				util.setCustomTabbar();
			}
		} else {
			if (!pass) {
				return false
			}
		}
		return true
	},

	// 搜索内容高亮显示
	//val：原数据   editKeyword：搜索关键字  color：字体颜色   Fsize：字体大小
	hightLight(val, editKeyword, color, Fsize) {
		// 使用 regexp 构造函数，因为这里要匹配的是一个变量
		const Reg = new RegExp(editKeyword, "ig");
		if (val) {
			const res = val.replace(Reg, `<span style="color: ${color};font-size:${Fsize}">${editKeyword}</span>`);
			return res;
		}
	}

}

export default util